package org.tio.sitexxx.web.server.controller.tiosite;

import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.UploadFile;
import org.tio.http.server.annotation.RequestPath;
import org.tio.sitexxx.im.server.handler.GroupChatReqHandler;
import org.tio.sitexxx.service.model.main.Blog;
import org.tio.sitexxx.service.model.main.BlogContent;
import org.tio.sitexxx.service.model.main.ChatRecord;
import org.tio.sitexxx.service.model.main.Img;
import org.tio.sitexxx.service.model.main.User;
import org.tio.sitexxx.service.service.ImgService;
import org.tio.sitexxx.service.service.base.UserRoleService;
import org.tio.sitexxx.service.service.base.UserService;
import org.tio.sitexxx.service.service.conf.ConfService;
import org.tio.sitexxx.service.service.tiosite.BlogContentService;
import org.tio.sitexxx.service.service.tiosite.BlogService;
import org.tio.sitexxx.service.vo.AppCode;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.service.vo.SimpleUser;
import org.tio.sitexxx.service.vo.editormd.UploadImgRet;
import org.tio.sitexxx.service.vo.im.CardLink;
import org.tio.sitexxx.service.vo.im.CardLink.ContentType;
import org.tio.sitexxx.web.server.utils.ImgUtils;
import org.tio.sitexxx.web.server.utils.UploadUtils;
import org.tio.sitexxx.web.server.utils.WebUtils;
import org.tio.utils.json.Json;
import org.tio.utils.resp.Resp;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.EscapeUtil;
import cn.hutool.core.util.ImageUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;

/**
 * @author tanyaowu
 * 2016年7月22日 上午10:44:13
 */
@RequestPath(value = BlogController.BEAN_PATH)
public class BlogController {

	public static final String	BEAN_PATH	= "/blog";
	private static Logger		log			= LoggerFactory.getLogger(BlogController.class);
	public static final String	SUBDIR_IMG	= org.tio.sitexxx.service.vo.Const.UPLOAD_DIR.BLOG_IMG;

	/**
	 *
	 * @author tanyaowu
	 */
	public BlogController() {
	}

	/**
	 * 查看某一篇博客
	 * @param id
	 * @param request
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	@RequestPath(value = "/{id}", forward = BEAN_PATH + "/getById")
	public Resp getById(Integer id, HttpRequest request) throws Exception {
		Record record = BlogService.me.getByIdWithMd(id);//.getById(id);
		if (record != null) {
			return Resp.ok(record);
		} else {
			return Resp.fail("没找到指定的博客");
		}
	}

	/**
	 * 查看某一篇博客的md数据
	 * @param id
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestPath(value = "/md/{id}", forward = BEAN_PATH + "/getMdById")
	public Resp getMdById(Integer id, HttpRequest request) throws Exception {
		BlogContent blogContent = BlogContentService.me.getByBlogId(id);
		if (blogContent != null) {
			return Resp.ok(blogContent);
		} else {
			return Resp.fail("没找到指定的博客内容");
		}
	}

	/**
	 * 
	 * @param blog
	 * @param blogContent
	 * @param request
	 * @param id 此字段有值时，表示是更新
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	@RequestPath(value = "/save")
	public Resp save(Blog blog, BlogContent blogContent, HttpRequest request, Integer id) throws Exception {
		String html = request.getParam("blogeditor_container-html-code");//blogContent.getHtml();  blogeditor_container-markdown-doc
		String md = request.getParam("blogeditor_container-markdown-doc");//blogContent.getMd();

		if (StrUtil.isBlank(md) || StrUtil.isBlank(html)) {
			return Resp.fail("内容为空");
		}
		blogContent.setMd(md);
		blogContent.setHtml(html);

		if (StrUtil.isBlank(blogContent.getTitle())) {
			return Resp.fail("请填写标题");
		}

		//不是原创 
		if (blog.getOriginal() == null) {
			//没有转载地址
			if (StrUtil.isBlank(blog.getFromurl())) {
				return Resp.fail("非原创，请注明转载地址哦");
			}
			//转载地址不是URL
			if (!Validator.isUrl(blog.getFromurl())) {
				return Resp.fail("转载地址不像个合法的URL");
			}

			blog.setOriginal((byte) 2);
		}

		User curr = WebUtils.currUser(request);


		blog.setStatus(Blog.Status.OK);

		if (blog.getOpen() == null) {
			blog.setOpen((byte) 2);
		}

		if (blog.getAllowcomment() == null) {
			blog.setAllowcomment((byte) 2);
		}

		blogContent.setTitle(EscapeUtil.escapeHtml4(blogContent.getTitle()));

		boolean isAdd = id == null;

		boolean f = false;
		if (isAdd) {
			blog.setUid(curr.getId());
			f = BlogService.me.save(blog, blogContent);
		} else {
			Blog blogInDb = BlogService.me.getById(id);
			//作者自己或者超管才能修改博客
			if (Objects.equals(curr.getId(), blogInDb.getUid()) || UserService.isSupper(curr)) {
				f = BlogService.me.update(blog, blogContent);
			} else {
				return Resp.fail("没权限操作").code(AppCode.ForbidOper.NOTPERMISSION);
			}
		}

		if (f) {
			//这儿加try防止可忽略性的需求影响正业务
			if (ObjectUtil.equal(blog.getOpen(), (byte) 1) && ObjectUtil.equal(blog.getStatus(), Blog.Status.OK)) {
				sendGroupChat(request, blog, blogContent, curr);

			}

			return Resp.ok(blog);
		} else {
			return Resp.fail("保存失败");
		}
	}

	private void sendGroupChat(HttpRequest request, Blog blog, BlogContent blogContent, User currUser) {
		String title = blogContent.getTitle();//"&lt;" + blogContent.getTitle() + "&gt;";
		String sum = HtmlUtil.cleanHtmlTag(blogContent.getHtml());
		sum = StrUtil.subWithLength(sum, 0, 512);

		CardLink cardLink = new CardLink();
		cardLink.setContentType(ContentType.blog);
		cardLink.setLink(Const.SITE + "/doc/" + blog.getId());
		cardLink.setSum(sum);
		cardLink.setTitle(title);
		String content = Json.toJson(cardLink);

		SimpleUser fromUser = SimpleUser.fromUser(currUser);
		String groupid = Const.GroupId.ALL;
		String channelContextId = org.tio.sitexxx.service.vo.Const.ChannelContextId.SYSTEM;

		GroupChatReqHandler.groupChatAndLog(request.getHttpSession().getId(), content, content, fromUser, request.getClientIp(), groupid, channelContextId,
		        ChatRecord.ContentType.CARD_LINK);
	}

	/**
	 * 博客编辑时，上传图片
	 * @param request
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	@RequestPath(value = "/uploadimg")
	public UploadImgRet uploadimg(HttpRequest request) throws Exception {
		try {
			UploadFile uploadFile = request.getUploadFile("editormd-image-file"); //editormd-image-file

			User curr = WebUtils.currUser(request);

			byte[] imageBytes = uploadFile.getData();
			String extName = FileUtil.extName(uploadFile.getName());

			UploadImgRet ret = null;
			if (UserService.isSupper(curr) || UserRoleService.hasRole(curr, Const.Role.UPLOAD_VIDEO)) {

			} else {
				int starttime = ConfService.getInt("blog.upload.img.starttime", 9);
				int endtime = ConfService.getInt("blog.upload.img.endtime", 22);
				int maxsize = ConfService.getInt("blog.upload.img.maxsize", 500);

				int hour = DateUtil.hour(new Date(), true);

				if (hour < starttime || hour >= endtime) {
					ret = UploadImgRet.fail("博客图片上传开放时间[" + starttime + ":00 - " + endtime + ":00]");
				}

				if (uploadFile.getSize() > 1024 * maxsize) {
					ret = UploadImgRet.fail("文件尺寸不能大于" + maxsize + "KB");
				}
			}

			Integer uid = null;
			if (curr != null) {
				uid = curr.getId();
			} else {
				uid = 1;
			}

			String imgUrlWithoutExt = UploadUtils.newFile(SUBDIR_IMG, uid, uploadFile.getName()); //不带后缀的文件路径
			String imgUrl = imgUrlWithoutExt + "." + extName;

			String smImgUrl = imgUrlWithoutExt + "_sm." + extName;

			String imgFilePath = Const.RES_ROOT + imgUrl; //文件路径
			FileUtil.writeBytes(imageBytes, imgFilePath);

			String smImgFilePath = Const.RES_ROOT + smImgUrl;

			BufferedImage bi = ImageUtil.toImage(imageBytes);
			float scale = ImgUtils.calcScaleWithWidth(1900, bi);

			Img img = ImgUtils.processImg(bi, imgFilePath, smImgFilePath, scale);
			img.setComefrom(Img.ComeFrom.BLOG_UPLOAD);
			img.setUid(uid);
			img.setCoverurl(smImgUrl);
			img.setUrl(imgUrl);
			img.setStatus((byte) 1);
			img.setSession(request.getHttpSession().getId());

			boolean f = ImgService.me.save(img);

			if (ret != null) {
				return ret;
			}

			if (curr == null) {
				ret = UploadImgRet.fail("服务器异常");
			} else {
				if (f) {
					ret = UploadImgRet.ok("上传成功", Const.RES_SERVER + imgUrl);
				} else {
					ret = UploadImgRet.fail("服务器异常");
				}
			}

			return ret;
		} catch (Exception e) {
			log.error(e.toString(), e);
			return UploadImgRet.fail("服务器异常");
		}

	}

	@RequestPath(value = "/getAccessCount")
	public Resp getAccessCount(HttpRequest request, Integer blogid) throws Exception {
		Integer accessCount = BlogService.me.getAccessCount(blogid);
		return Resp.ok(accessCount);
	}

	/**
	 * 分页查询博客列表
	 * @param request
	 * @param pageNumber
	 * @param pageSize
	 * @param uid 如果有值 ，则只查该用户的博客
	 * @return
	 * @throws Exception
	 */
	@RequestPath(value = "/page")
	public Resp page(HttpRequest request, Integer pageNumber, Integer pageSize, Integer uid) throws Exception {
		Page<Record> page = BlogService.me.page(pageNumber, pageSize, uid);
		return Resp.ok(page);
	}

}
